# 对main的改进
import glob
import numpy as np
import os
import shutil
from utils import log_progress
import glob
import numpy as np
import os
import shutil
from utils import log_progress
import tensorflow as tf
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.models import Sequential
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img
#一定要加，不然出错
config = tf.compat.v1.ConfigProto(allow_soft_placement = True)
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config = config)

IMG_DIM = (150, 150) # 图片的大小

train_files = glob.glob('F:\\dogsvscats\\training_data\\*')
# 加载图片，然后转换成数组,每一张都是(150,150,3)
train_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in train_files]
train_imgs = np.array(train_imgs)# 列表转array
train_labels = [fn.split('\\')[3].split('.')[0].strip() for fn in train_files]# 下面的3，根据目录层次来决定

validation_files = glob.glob('F:\\dogsvscats\\validation_data\\*')
validation_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in validation_files]
validation_imgs = np.array(validation_imgs)
validation_labels = [fn.split('\\')[3].split('.')[0].strip() for fn in validation_files]

print('Train dataset shape:', train_imgs.shape,
      '\tValidation dataset shape:', validation_imgs.shape)
train_imgs_scaled = train_imgs.astype('float32') # 转为float32类型
validation_imgs_scaled  = validation_imgs.astype('float32')
train_imgs_scaled /= 255 # 归一化
validation_imgs_scaled /= 255
print(train_imgs[0].shape)
array_to_img(train_imgs[0]) # 数组转成图片

batch_size = 60
num_classes = 2
epochs = 50
input_shape = (150, 150, 3)
# encode text category labels
from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()
le.fit(train_labels)
# 把标签转换为0,1类别
train_labels_enc = le.transform(train_labels)
validation_labels_enc = le.transform(validation_labels)
model = Sequential()

model.add(Conv2D(16, kernel_size=(3, 3), activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# 设置编译的参数
model.compile(loss='binary_crossentropy',
              optimizer=optimizers.RMSprop(),
              metrics=['accuracy'])
# model.summary()输出模型各层的参数状况
model.summary()
history = model.fit(x=train_imgs_scaled, y=train_labels_enc,
                    validation_data=(validation_imgs_scaled, validation_labels_enc),
                    batch_size=batch_size,epochs=epochs,verbose=1)
model.save('cats_dogs_basic_cnn.h5')
# 2s 23ms/step - loss: 0.0212 - accuracy: 0.9948 - val_loss: 1.3823 - val_accuracy: 0.7633